/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ExJoRmPanel.java
 *
 * Created on 29/11/2011, 22:59:33
 */

package proj5labbd.graphics.exibicaoJornal;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class ExJoRmPanel extends OperationPanel {

    /** Creates new form ExJoRmPanel */
    public ExJoRmPanel(ExJoFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbtRemove.addActionListener(new ExJoAction());
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
                                     
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnParam = new javax.swing.JPanel();
        jlbData = new javax.swing.JLabel();
        jlbHoraIn = new javax.swing.JLabel();
        jlbJornal = new javax.swing.JLabel();
        jlbFuncionario = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jlbIbope = new javax.swing.JLabel();
        jtxtIbope = new javax.swing.JTextField();
        jftxtDate = new javax.swing.JFormattedTextField();
        jftxtIni = new javax.swing.JFormattedTextField();
        jftxtFim = new javax.swing.JFormattedTextField();
        jtxtJornal = new javax.swing.JTextField();
        jtxtApresentador = new javax.swing.JTextField();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtbRemove = new javax.swing.JTable();
        jbtRemove = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Remoção"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnParam.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de remoção"));

        jlbData.setText("Data");

        jlbHoraIn.setText("Hora de início");

        jlbJornal.setText("Jornal");

        jlbFuncionario.setText("Apresentador");

        jLabel1.setText("Hora de término");

        jlbIbope.setText("Ibope");

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtDate.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtIni.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtIni.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtFim.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpnParamLayout = new javax.swing.GroupLayout(jpnParam);
        jpnParam.setLayout(jpnParamLayout);
        jpnParamLayout.setHorizontalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jtxtJornal, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbData, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jftxtIni)
                            .addComponent(jlbHoraIn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jlbJornal))
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbIbope, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jtxtIbope, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jlbFuncionario)
                        .addComponent(jtxtApresentador, javax.swing.GroupLayout.PREFERRED_SIZE, 291, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jpnParamLayout.setVerticalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbData)
                    .addComponent(jLabel1)
                    .addComponent(jlbHoraIn)
                    .addComponent(jlbIbope))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtIbope, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbJornal)
                    .addComponent(jlbFuncionario))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtJornal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtApresentador, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jtbRemove.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane3.setViewportView(jtbRemove);

        jbtRemove.setText("Remover");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 597, Short.MAX_VALUE)
                    .addComponent(jpnParam, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jbtRemove, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jpnParam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtRemove)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
    /*
     * Resgata as informações das tabelas que serão exibidas
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        try {
                // TODO add your handling code here:
                setupTable();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações da tabela");
                frame.printException(ex);
            }
    }//GEN-LAST:event_formComponentShown

    /*
     * Trata os eventos do mouse
     */
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbRemove.clearSelection();
    }//GEN-LAST:event_formMouseClicked
    
    /*
     * Formata a tabela exibicaoJornal
     */
    public void setupTable() throws SQLException {

        String [] fields = {"exibicaoJornal.idPr","exibicaoJornal.idFu","exibicaoJornal.dataExJo",
            "exibicaoJornal.horaInicioExJo","exibicaoJornal.horaFimExJo","exibicaoJornal.ibopeExJo"
        };
        String [] titles = {"ID Jornal","ID Funcionario","Data","Hora Inicio","Hora Fim", "Ibope"};
        String [] params = {"exibicaoJornal.idPr = jornal.idPr", "exibicaoJornal.idFu = funcionario.idFu"};
        String [][] result = dbInterface.view(fields,params,new String[]{"exibicaoJornal","jornal","funcionario"});

        DefaultTableModel model = new DefaultTableModel(result,titles);
        jtbRemove.setModel(model);

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jbtRemove;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JFormattedTextField jftxtFim;
    private javax.swing.JFormattedTextField jftxtIni;
    private javax.swing.JLabel jlbData;
    private javax.swing.JLabel jlbFuncionario;
    private javax.swing.JLabel jlbHoraIn;
    private javax.swing.JLabel jlbIbope;
    private javax.swing.JLabel jlbJornal;
    private javax.swing.JPanel jpnParam;
    private javax.swing.JTable jtbRemove;
    private javax.swing.JTextField jtxtApresentador;
    private javax.swing.JTextField jtxtIbope;
    private javax.swing.JTextField jtxtJornal;
    // End of variables declaration//GEN-END:variables

    class ExJoAction implements ActionListener {

        /*
         * Controla os eventos de remoção
         */
        public void actionPerformed(ActionEvent e) {
            ArrayList<String> param = new ArrayList<String>();

                if (jftxtDate.getText().compareTo("  -  -    ") != 0) {
                    param.add("exibicaoJornal.dataExJo="+"TO_DATE('"+jftxtDate.getText()+"','DD-MM-YYYY')");
                }
                if (jftxtIni.getText().compareTo("  :  ") != 0) {
                    param.add("exibicaoJornal.horaInicioExJo='"+jftxtIni.getText()+"'");
                }
                if (jftxtFim.getText().compareTo("  :  ") != 0) {
                    param.add("exibicaoJornal.horaFimExJo='"+jftxtFim.getText()+"'");
                }
                if (jtxtIbope.getText().trim().compareTo("") != 0) {
                    param.add("exibicaoJornal.ibopeExJo="+"TO_NUMBER('"+jtxtIbope.getText()+"')");
                }
                if (jtxtJornal.getText().trim().compareTo("") != 0) {
                    try {
                        String[][] s = dbInterface.view(new String[]{"idPr"}, 
                                new String[]{"UPPER(jornal.tituloPr)=UPPER('" + jtxtJornal.getText() + "')"},
                                new String[]{"jornal"});
                        param.add("exibicaoJornal.idPr="+s[0][0]);
                    } catch (SQLException ex) {
                        Logger.getLogger(ExJoRmPanel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if (jtxtApresentador.getText().trim().compareTo("") != 0) {
                    try {
                        String[][] s = dbInterface.view(new String[]{"idFu"}, 
                                new String[]{"UPPER(funcionario.nomeCompletoFu)=UPPER('" + jtxtApresentador.getText() + "')"},
                                new String[]{"funcionario"});
                        param.add("exibicaoJornal.idFu="+s[0][0]);
                    } catch (SQLException ex) {
                        Logger.getLogger(ExJoRmPanel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                
                if (param.size() > 0) {
                    try {
                        String[] paramArray = new String[param.size()];
                        param.toArray(paramArray);
                        dbInterface.remove(paramArray, new String[]{"exibicaoJornal"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao remover as tuplas desejadas.");
                    }
                } else {

                    if (jtbRemove.getSelectedRowCount() > 1) {
                    JOptionPane.showMessageDialog(null, "Você deve selecionar apenas uma linha da tabela.");
                    }
                    else if (jtbRemove.getSelectedRowCount() == 1) {
                        try {
                            String[] params = new String[4];
                            params[0] = "idPr=" + jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 0);
                            params[1] = "idFu=" + jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 1);
                            params[2] = "dataExJo=TO_DATE('" + jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 2).toString().substring(0,10)
                                            +"', 'YYYY-MM-DD')";
                            params[3] = "horaInicioExJo='"+jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 3)+"'";
                            dbInterface.remove(params, new String[]{"exibicaoJornal"});
                        } catch (SQLException ex) {
                            frame.printException(ex);
                            JOptionPane.showMessageDialog(null, "Erro ao tentar remover a tupla.");
                        }
                    }
                    else if (jtbRemove.getSelectedRowCount() == 0) {
                        JOptionPane.showMessageDialog(null, "Você deve escolhar uma tupla ou um parâmetro para a remoção.");
                    }
                }
                
            try {
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }

        }
    }

    
}
